<template>
  <div class="main-content voucher-list-wrapper">
    <div class="filter-box">
      <p class="title">算力券账单</p>

      <el-form :inline="true" :model="form">
        <div class="item">
          <el-form-item label="类型">
            <el-select
              v-model="form.type"
              placeholder="请选择"
              clearable
              @clear="searchFn"
            >
              <el-option label="划拨" value="TRANSFER" />
              <el-option label="赠送" value="GIVE" />
            </el-select>
          </el-form-item>
          <el-form-item label="当前状态">
            <el-select
              v-model="form.state"
              placeholder="请选择"
              clearable
              @clear="searchFn"
            >
              <el-option label="正在处理" value="DOING" />
              <el-option label="划拨成功" value="OK" />
              <el-option label="划拨失败" value="FAIL" />
            </el-select>
          </el-form-item>

          <el-form-item label="划拨身份">
            <el-select
              v-model="form.fromUserType"
              placeholder="请选择"
              clearable
              @clear="searchFn"
            >
              <el-option label="代理商" value="PARTNER" />
              <el-option label="管理员" value="ADMIN" />
            </el-select>
          </el-form-item>
        </div>
        <div class="item">
          <el-form-item label="划拨时间">
            <el-date-picker
              v-model="form.date"
              type="daterange"
              range-separator="至"
              value-format="YYYY-MM-DD"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              @change="changeDate"
            />
          </el-form-item>
          <el-form-item label="收款对象">
            <el-select
              style="width:100px;"
              v-model="form.toUserType"
              placeholder="请选择"
              clearable
              @clear="searchFn"
            >
              <el-option label="代理商" value="PARTNER" />
              <el-option label="直客" value="CUSTOMER" />
            </el-select>
            <el-form-item label="">
              <el-input
                v-model="form.toNickname"
                placeholder="请输入收款对象"
                clearable
                @clear="searchFn"
              />
            </el-form-item>
          </el-form-item>

          <!-- 操作 -->
          <div class="btn-box">
            <el-button
              type="primary"
              @click="searchFn">
              查询
            </el-button>
            <!-- 重置 -->
            <el-button
              type=""
              @click="restFn">
              重置
            </el-button>

          </div>
        </div>
      </el-form>
    </div>

    <div class="content-box">

      <div class="top-box">
        <!-- 标题 -->
        <div class="title">算力券划拨记录</div>
        <div class="exportFn" @click="exportFn"> 
          导出Excel
        </div>
      </div>
      
      <ct-table :options="tableOptions">
        <template v-slot:index="scope">
          <span>{{ scope.row.index }}</span>
        </template>
        <template v-slot:type="scope">
          <span>{{ scope.row.type === 1 ? "直客" : "伙伴" }}</span>
        </template>
        <template v-slot:style="scope">
          <span>{{ handleStyle(scope.row.style) }}</span>
        </template>
        <template v-slot:operate="scope">
            <el-text
              type="primary"
              @click="toDetail(scope.row)">
              详情
            </el-text>
          </template>
      </ct-table>
      <div class="total-box">
        <div class="total-text">充值金额合计：{{ data_bottom.userRechargeTotal }}元</div>
        <div class="total-text">划拨金额合计：{{ data_bottom.voucherTotal }}元</div>
      </div>
      <ct-pagination :options="pageOptions" :pageEvent="getListData">
      </ct-pagination>
    </div>
  </div>
</template>

<script setup>
import axios from "axios";
import { getVoucherList, voucherExport } from "@/api/index";

import CtTable from "@/components/CtTable.vue";
import CtPagination from "@/components/Pagination.vue";

const { proxy } = getCurrentInstance();

import { usePageOptions } from "@/hooks/usePageOptions";
import { ElMessage } from "element-plus";
const { pageOptions } = usePageOptions();

let form = ref({
  accountName: "",
  date: "",
  start: "",
  end: "",
  type: "",
  style: "",
  state: "",
  fromUserType:"",
  toNickname:"",
  toUserType:""
});

let data_bottom = ref({
  userRechargeTotal:"",
  voucherTotal:""
})
let data_bottom1 = ref({
  userRechargeTotal:"",
  voucherTotal:""
})

const styleOptions = reactive([
  {
    label: "赠送",
    value: 1,
  },
  {
    label: "充值",
    value: 2,
  },
  {
    label: "抵扣",
    value: 3,
  },
  {
    label: "退款",
    value: 4,
  },
]);

function handleStyle(style) {
  const findItem = styleOptions.find((item) => item.value === style);
  return findItem ? findItem.label : "";
}

function exportFn() {
  const { currentPage, pageSize } = pageOptions;
  const {start, end,state,type,toUserType,toNickname,fromUserType } = form.value;

  axios({
    url: "/api/v2/exportVoucherList",
    params: {
      endTime:end,
      fromUserType,
      page:currentPage ,
      pageSize,
      startTime:start,
      state:state,
      toNickname,
      toUserType,
      type,
    },
    headers: {
      token: localStorage.getItem("token"),
    },
    responseType: "blob",
  })
    .then((res) => {
      if (res.status === 200) {
        const content = res.data;
        const blob = new Blob([content], {
          // 下载的文件格式自己在这边更改type的值就好了
          type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
        });

        const date = new Date();
        const year = date.getFullYear();
        let month = date.getMonth() + 1;
        month = month < 10 ? "0" + month : month;
        let day = date.getDate();
        day = day < 10 ? "0" + day : day;
        let hour = date.getHours();
        hour = hour < 10 ? "0" + hour : hour;
        let minute = date.getMinutes();
        minute = minute < 10 ? "0" + minute : minute;
        let second = date.getSeconds();
        second = second < 10 ? "0" + second : second;
        const filename = `算力券账单_${year}${month}${day}${hour}${minute}${second}.xlsx`;

        const elink = document.createElement("a");
        elink.download = filename;
        elink.style.display = "none";
        elink.href = URL.createObjectURL(blob);
        document.body.appendChild(elink);
        elink.click();
        URL.revokeObjectURL(elink.href);
        document.body.removeChild(elink);
      } else {
        ElMessage.error("导出失败，请稍后重试");
      }
    })
    .catch((r) => {
      console.error("导出失败---", r);
    });
}

let tableOptions = reactive({
  data: [],
  loading: false,
  columns: [
    {
      label: "序号",
      prop: "index",
      width: 80,
      isCustom: true,
    },
    {
      label: "划拨方",
      prop: "fromNickname",
    },
    {
      label: "划拨身份",
      prop: "fromUserType",
    },
    {
      label: "类型",
      prop: "type",
    },
    {
      label: "收款对象",
      prop: "toNickname",
    },
    {
      label: "收款方身份",
      prop: "toUserType",
    },
    {
      label: "充值金额(元)",
      prop: "userRecharge",
    },
    {
      label: "划拨金额(元)",
      prop: "voucherMoney",
    },
    {
      label: "折扣",
      prop: "discountRatio",
    },
    {
      label: "当前状态",
      prop: "state",
    },
    {
      label: "划拨时间",
      prop: "createdAt",
    },
    {
      label: "备注",
      prop: "remark",
    },

  ],
});
function restFn(){
  form.value={
    accountName: "",
    date: "",
    start: "",
    end: "",
    type: "",
    style: "",
    state: ""
  }
  searchFn();
}
function getListData() {
  tableOptions.loading = true;
  const { currentPage, pageSize } = pageOptions;
  const {start, end,state,type,toUserType,toNickname,fromUserType } = form.value;

  getVoucherList({
    // accountName,
    endTime:end,
    page:currentPage ,
    state:state,
    type,
    pageSize,
    startTime:start,
    toUserType,
    toNickname,
    fromUserType
  })
    .then((res) => {
      const { content, totalElements,data } = res.data;
      if (content.length) {
        for (let i = 0; i < content.length; i++) {
          content[i].index = proxy.$handleIndex(i, pageOptions);

        }
      }
      tableOptions.data = content;
      tableOptions.loading = false;
      pageOptions.total = totalElements;
      data_bottom.value = data? JSON.parse(data):data_bottom1.value;
      console.log(tableOptions.data,'5555')
    })
    .catch(() => {
      tableOptions.loading = false;
    });
}

const searchFn = proxy.$debounce(() => {
  tableOptions.data = [];
  pageOptions.currentPage = 1;
  pageOptions.total = 0;

  getListData();
});

function changeDate(value) {
  if (value) {
    form.value.start = value[0] + " 00:00:00";
    form.value.end = value[1] + " 23:59:59";
  } else {
    form.value.start = "";
    form.value.end = "";
  }

  searchFn();
}

onMounted(() => {
  getListData();
});
</script>

<style lang="scss" scoped>
.voucher-list-wrapper {
  .content-box {
    position: relative;
    .top-box {
      width: 100%;
      // display: flex;
      // justify-content: flex-end;
      .title{
        font-size: 16px;
        float: left;
      }
      .exportFn{
        float:right;
        cursor:pointer;
        color:#00a8ff;
      }
      .data-box{
        float: left;
        .item{
          font-size: 14px;
          line-height: 18px;
          color: var(--color-font-color);
          margin: auto 10px;
          float: left;
        }
      }
      .export-btn{
        float: right;
      }
    }
    .total-box{
      position:absolute;
      bottom: 10px;
      .total-text{
        float: left;
        margin: 20px;
      }
    }
  }
}
.btn-box{
  margin-top: -20px;
}
</style>
